﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AgentyWeb.Models;
using System.Web.Script.Services;

namespace AgentyWeb
{
    /// <summary>
    /// Summary description for Locations
    /// </summary>
    /// 

    [WebService(Namespace = "http://localhost:1542/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class Locations : System.Web.Services.WebService
    {

        private string conn = @"Data Source=192.168.1.225;Initial Catalog=Agenty;Integrated Security=False;User ID=agenty;Password=agenty;MultipleActiveResultSets=True";

        [WebMethod]
        [ScriptMethod]
        public string Register(string nickname, string color)
        {
            LocationsDb db = new LocationsDb(conn);
            Session registeredSession = new Session() { Nickname = nickname, Color = color };
            Guid guid = Guid.NewGuid();
            string sid = guid.ToString();
            registeredSession.SessionId = guid;

            db.Sessions.Add(registeredSession);
            db.SaveChanges();
            return sid;
        }

        [WebMethod]
        [ScriptMethod]
        public void AddLocation(string sid, double lat, double lon)
        {
            LocationsDb db = new LocationsDb(conn);
            Session session = db.Sessions.Find(Guid.Parse(sid));
            if (session != null)
            {
                session.Locations.Add(new LocationReport() { Latitude = lat, Longitude = lon, Time = DateTime.Now });
                db.SaveChanges();
            }
        }

        [WebMethod]
        public List<Session> GetDataSince(DateTime when)
        {
            LocationsDb db = new LocationsDb(conn);
            foreach (Session session in db.Sessions)
                session.Locations = session.Locations.Where(l => l.Time >= when).ToList();
            IEnumerable<Session> ret = db.Sessions.Where(s => s.Locations.Any());
            return ret.Select(s => s.PureClone()).ToList();
        }

        [WebMethod]
        public List<Session> GetDataBetween(DateTime from, DateTime to)
        {
            LocationsDb db = new LocationsDb(conn);
            foreach (Session session in db.Sessions)
                session.Locations = session.Locations.Where(l => l.Time >= from && l.Time <= to).ToList();
            IEnumerable<Session> ret = db.Sessions.Where(s => s.Locations.Any());
            return ret.Select(s => s.PureClone()).ToList();
        }
    }
}
